package com.marco.ipdata.service.impl;

import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.collect.Maps;
import com.marco.commons.SpringContextUtils;
import com.marco.ipdata.runnable.BaiduApiRunnable;
import com.marco.ipdata.runnable.TaobaoApiRunnable;
import com.marco.ipdata.service.AbstractApiService;
import com.marco.ipdata.service.ChinaIPService;
import com.marco.system.service.NormalizationService;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;

/**
 * TaobaoApiServiceImpl.java
 * Create on 2017/3/28
 * Copyright(c) JD Inc 2017. All Rights Reserved.
 * <pre>
 * 功能说明：此service处理淘宝接口的调用以及返回结果分析
 * </pre>
 */
@Service
@Transactional
public class TaobaoApiServiceImpl extends AbstractApiService {
    private static final Logger logger = LoggerFactory.getLogger(TaobaoApiServiceImpl.class);
    private static final ObjectMapper jsonParaser = new ObjectMapper();
    private static final String IP_URL = "http://ip.taobao.com/service/getIpInfo.php";
    private static final String TABLE_NAME = "api_ip_taobao";//淘宝数据存储的表名
    private static final Integer TAGS = 2;//淘宝接口的标记

    @Autowired
    private ChinaIPService chinaIPService;
    @Autowired
    private ThreadPoolTaskExecutor executor;
    @Autowired
    private NormalizationService normalizationService;
    // 公用线程池配置
    @Value("${executor.queue.capacity}")
    private Integer executorQueueCapacity;

    @Override
    public void obtainApiDataByParam() {
        try {
            TaobaoApiRunnable runnable = (TaobaoApiRunnable) SpringContextUtils.getBeanById("taobaoApiRunnable");
            runnable.setStartIndex(0);
            runnable.setEndIndex(chinaIPService.totalCounts());
            runnable.setThreadName("淘宝线程");
            while (executor.getThreadPoolExecutor().getQueue().size() >= executorQueueCapacity) {
                try {
                    Thread.sleep(10000);
                } catch (InterruptedException e) {
                    logger.error("发送消息任务信息:线程等待出现异常", e);
                }
            }
            executor.execute(runnable);
        } catch (Exception e) {
            throw new RuntimeException("调用百度API接口出现异常", e);
        }
    }

    @Override
    protected Map<String, String> resolveResult(String result) {
        Map<String, String> res = Maps.newHashMap();
        String isp = "未知";
        String ad = "";
        try {
            //对淘宝返回的结果进行解析，并进行封装
            if (StringUtils.isBlank(result)) {
                res.put("isp", isp);
                res.put("ad", ad);
                return res;
            }
            Map resultMap = jsonParaser.readValue(result, Map.class);
            //状态为0表示返回正常
            if (resultMap.get("code").toString().equals("0")) {
                Map data = (Map) resultMap.get("data");
                String nationCode = data.get("country_id").toString();
                StringBuilder sb = new StringBuilder();//中国IP
                sb.append(data.get("region")).append(data.get("city")).append(data.get("county"));
                if (nationCode.matches("CN|TW|HK|MO")) {
                    isp = normalizationService.formatISP((String) data.get("isp"));
                    ad = sb.toString();
                }
            }
        } catch (Exception e) {
            logger.error("解析API 返回结果出现异常", e);
        }
        res.put("isp", isp);
        res.put("ad", ad);
        return res;
    }

    @Override
    protected Logger getLogger() {
        return logger;
    }

    @Override
    protected String url() {
        return IP_URL;
    }

    @Override
    protected Integer tags() {
        return TAGS;
    }

    @Override
    protected String tableName() {
        return TABLE_NAME;
    }
}
